package com.yunc.common.oss;

import cn.hutool.core.date.DateUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.yunc.common.exception.UCException;
import com.yunc.common.properties.Pro;
import com.yunc.common.utils.BaseUtil;
import com.yunc.common.utils.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * @author taocongcong
 * @create 2018-11-12 14:04
 */
@Service
public class QcloudCloudStorageService {

    @Autowired
    private Pro pro;

    private COSClient client;

    @PostConstruct
    private void init(){
        COSCredentials cred = new BasicCOSCredentials(pro.getQcloudSecretId(),
                pro.getQcloudSecretKey());
        // 初始化客户端配置
        ClientConfig clientConfig = new ClientConfig();
        // 设置bucket所在的区域
        clientConfig.setRegion(new Region(pro.getQcloudRegion()));
        client = new COSClient(cred, clientConfig);
    }

    public String upload(byte[] data, String path) {
        // 腾讯云必需要以"/"开头
        if(!path.startsWith("/")) {
            path = "/" + path;
        }
        // 上传到腾讯云
        /*UploadFileRequest request = new UploadFileRequest(pro.getQcloudBucketName(), path, data);
        String response = client.uploadFile(request);
        PutObjectRequest putObjectRequest = new PutObjectRequest(pro.getQcloudBucketName(), path, data);
        PutObjectResult putObjectResult = client.putObject(putObjectRequest);
        JSONObject jsonObject = JSONObject.fromObject(response);
        if(jsonObject.getInt("code") != 0) {
            throw new UCException("文件上传失败，" + jsonObject.getString("message"));
        }*/
        return pro.getQcloudDomain() + path;
    }

    public String upload(InputStream inputStream, String path) {
        String newFileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") +
                BaseUtil.acceptRandom(BaseUtil.NUMBER_CONTENT, 6) + "." +
                BaseUtil.acceptFileType(path);
        if(!newFileName.startsWith("/")) {
            newFileName = "/" + newFileName;
        }
        // 上传到腾讯云
        ObjectMetadata objectMetadata = new ObjectMetadata();
        try {
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(PathUtil.getcontentType(BaseUtil.acceptFileType(newFileName)));
            objectMetadata.setContentDisposition("inline;filename=" + newFileName);
            PutObjectRequest putObjectRequest = new PutObjectRequest(pro.getQcloudBucketName(), newFileName, inputStream, objectMetadata);
            PutObjectResult putObjectResult = client.putObject(putObjectRequest);
            String eTag = putObjectResult.getETag();
            String url = getUrl(eTag);
            String newUrl = url.substring(0, url.indexOf("?"));
            String nUrl = pro.getQcloudDomain() + newFileName;
            return nUrl;
        } catch (IOException e) {
            e.printStackTrace();
            throw new UCException("上传至腾讯云失败");
        }

    }

    public String upload(byte[] data) {
        return upload(data, PathUtil.getPath(pro.getQcloudPrefix()));
    }

    public String upload(InputStream inputStream) {
        return upload(inputStream, PathUtil.getPath(pro.getQcloudPrefix()));
    }

    public String getUrl(String key) {
        // 设置URL过期时间为10年 3600l* 1000*24*365*10
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = client.generatePresignedUrl(pro.getQcloudBucketName(), key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }
}
